<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :inline="true" v-model="listQuery" class="search" size="mini">
        <el-row>
          <el-col :span="6">
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
                >新增</el-button
              >
            </el-form-item>
            <el-form-item label="">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                :disabled="selections.length===0"
                @click="handleBatchDelete"
                >批量删除</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="">
              <el-input
                v-model="listQuery.name"
                placeholder="请输入收款单号"
                clearable
                @keyup.enter.native="handleFilter"
              ></el-input>
            </el-form-item>
            <el-form-item label="">
              <el-select
                v-model="listQuery.customer"
                placeholder="客户"
                clearable
                filterable
              >
                <el-option
                  v-for="item in customers"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="">
              <el-select
                v-model="listQuery.user"
                placeholder="收款人"
                clearable
              >
                <el-option
                  v-for="item in users"
                  :key="item.id"
                  :label="item.real_name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="">
              <el-date-picker
                v-model="listQuery.search_date"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="">
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click.native="handleFilter"
                >查询</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
        
      </el-form>
      <!-- 上部 -->
      <el-table
        :data="datas"
        border
        stripe
        v-loading="listLoading"
        highlight-current-row
        style="width: 100%"
        size="mini"
        max-height="580"
        @selection-change="handleSelectionChange"
        show-summary
        :summary-method="getSummaries"
      >
        <el-table-column type="expand" width="30">
          <template slot-scope="props">
            <div style="padding-left: 60px; width: 80%">
              <el-tabs v-model="activeItem">
                <el-tab-pane label="销售收款明细" name="1">
                  <el-table
                    :data="props.row.details"
                    border
                    stripe
                    size="mini"
                    highlight-current-row
                    style="width: 90%"
                  >
                    <el-table-column type="index" width="50" align="center" />
                    <el-table-column
                      prop="receipt_order_code"
                      label="收款单编号"
                      width="140"
                    />
                    <el-table-column
                      property="receipt_order_time"
                      label="收款日期"
                      width="120"
                    />
                    <el-table-column
                      property="amount"
                      label="本次付款金额"
                      width="120"
                    />
                    <el-table-column
                      property="receipt_order_account_name"
                      label="收款账号"
                      width="120"
                    />
                    <el-table-column property="sale_order_code" label="单据编号">
                      <template slot-scope="scope">
                          <span v-if="scope.row.category==0">{{scope.row.sale_order_code}}</span>
                          <span v-else>{{scope.row.prepay_code}}</span>
                      </template>
                    </el-table-column>
                    <el-table-column
                      property="flag_name"
                      label="单据类型"
                    />
                    <el-table-column property="remark" label="说明" />
                  </el-table>
                </el-tab-pane>
              </el-tabs>
            </div>
          </template>
        </el-table-column>
        <el-table-column type="selection" align="center"> </el-table-column>

        <el-table-column
          v-for="column in tableColumns"
          :key="column.key"
          :label="column.title"
          :prop="column.key"
          :align="column.align"
          :width="column.width ? column.width : ''"
        >
          <template slot-scope="scope">
            <div v-if="column.key == 'code'">
              <el-link type="primary" @click="handleEdit(scope)" size="mini">{{
                scope.row[column.key]
              }}</el-link>
            </div>
            <div v-else>
              {{ dataFormatter(column.key, scope.row[column.key]) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="120px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="handleEdit(scope)"
            ></el-button>
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="handleDelete(scope)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 对话框 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="getTitle"
      width="85%"
      top="10px"
      :close-on-click-modal="false"
    >
      <el-row style="margin-bottom: 10px; margin-top: -30px">
        <el-col :span="12" :offset="1">
          <el-button-group>
            <el-button
              type="primary"
              size="small"
              plain
              :disabled="form.sale_order_code != null"
              @click="handleSave(false)"
              >保存</el-button
            >
            <el-button
              type="primary"
              size="small"
              plain
              :disabled="form.sale_order_code != null"
              @click="handleSave(true)"
              >保存并新增</el-button
            >
            <el-button
              type="danger"
              size="small"
              plain
              @click="dialogVisible = false"
              >关闭</el-button
            >
          </el-button-group>
        </el-col>
      </el-row>
      <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="120px"
        label-position="right"
        style="padding: 0 20px"
        status-icon
        size="mini"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="收款单编号" prop="code">
              <el-input
                type="text"
                v-model="form.code"
                placeholder="收款单编号"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="收款账号" prop="account">
              <el-select v-model="form.account" placeholder="收款账号">
                <el-option
                  v-for="item in accounts"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="收款时间" prop="recv_time">
              <el-date-picker
                v-model="form.recv_time"
                type="date"
                placeholder="收款时间"
                clearable
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="付款客户" prop="customer">
              <el-select
                v-model="form.customer"
                placeholder="付款客户"
                clearable
                filterable
              >
                <el-option
                  v-for="item in customers"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="收款人" prop="user">
              <el-select v-model="form.user" placeholder="收款人" clearable>
                <el-option
                  v-for="item in users"
                  :label="item.real_name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="应收款金额" prop="receivable">
              <el-input
                v-model="form.receivable"
                placeholder="应收款金额"
                clearable
                disabled
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="本次收款金额" prop="amount">
              <el-input
                v-model="form.amount"
                placeholder="本次收款金额"
                clearable
                disabled
                @input="form.amount = form.amount.replace(/[^\d|.]/g, '')"
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="优惠金额" prop="discount_amount">
              <el-input
                v-model="form.discount_amount"
                placeholder="优惠金额"
                clearable
                disabled

              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实际收款金额" prop="actual_amount">
              <el-input
                v-model="form.actual_amount"
                placeholder="实际收款金额"
                clearable
                @input="discountInput"
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item label="说明" prop="remark">
              <el-input v-model="form.remark" placeholder="说明"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="bottom">
          <el-tabs v-model="activeName">
            <el-tab-pane label="收款明细" name="first">
              <el-row>
                <el-col :span="12">
                  <el-button-group>
                    <el-button
                      size="small"
                      type="primary"
                      plain
                      v-if="form.sale_order_code == null"
                      @click="handleSelectCode"
                      >选择销售出库单</el-button
                    >
                    <el-button
                      plain
                      type="primary"
                      size="small"
                      v-if="form.sale_order_code == null"
                      @click="deleteItem"
                      >删除</el-button
                    >
                  </el-button-group>
                </el-col>
              </el-row>
              <el-table
                :data="form.details"
                border
                highlight-current-row
                style="width: 100%"
                size="mini"
                id="detail"
                @selection-change="handleItemChange"
              >
                <el-table-column type="selection" width="40"></el-table-column>
                <el-table-column label="单据编号" align="center" width="180">
                  <template slot-scope="scope">
                    <el-form-item label-width="0">
                      <el-input
                        v-if="scope.row.category==0"
                        v-model="scope.row.sale_order_code"
                        disabled
                        size="small"
                      ></el-input>
                      <el-input
                        v-else
                        v-model="scope.row.prepay_code"
                        disabled
                        size="small"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="单据时间" align="center" width="140">
                  <template slot-scope="scope">
                    <el-form-item label-width="0">
                      <el-input
                        v-if="scope.row.category==0"
                        v-model="scope.row.sale_order_time"
                        disabled
                        size="small"
                      ></el-input>
                      <el-input
                        v-else
                        v-model="scope.row.receipt_order_time"
                        disabled
                        size="small"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="单据金额" align="center" width="120">
                  <template slot-scope="scope">
                    <el-form-item label-width="0">
                      <el-input
                        v-if="scope.row.category==0"
                        v-model="scope.row.sale_order_total_amount"
                        disabled
                        size="small"
                      ></el-input>
                      <el-input
                        v-else
                        v-model="scope.row.prepay_total_amount"
                        disabled
                        size="small"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="已付款金额" align="center" width="120">
                  <template slot-scope="scope">
                    <el-form-item label-width="0">
                      <el-input
                        v-model="scope.row.sale_order_amount"
                        placeholder=""
                        disabled
                        size="small"
                      ></el-input>
                      
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="本次付款金额"
                  align="center"
                  width="160"
                >
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="'details.' + scope.$index + '.amount'"
                      label-width="0"
                      :rules="formRules.amount"
                    >
                      <el-input
                        v-model="scope.row.amount"
                        placeholder=""
                        clearable
                        size="small"
                        @input="calcAmounts"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="备注说明" align="center">
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="'details.' + scope.$index + '.remark'"
                      label-width="0"
                    >
                      <el-input
                        v-model="scope.row.remark"
                        placeholder=""
                        clearable
                        size="small"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-form>
    </el-dialog>
    <el-dialog
      title="选择销售出库单"
      :visible.sync="dlgCodeVisible"
      top="5vh"
      width="80%"
    >
      <sale-order
        :dlgCodeVisible.sync="dlgCodeVisible"
        @selections="getSelections"
        ref="order"
      >
      </sale-order>
    </el-dialog>
  </div>
</template>

<script>
import moment from "moment";
import { mapGetters } from "vuex";
import { pickerOptions } from "@/utils/const";
import SaleOrder from "@/views/components/SaleOrder";

import {
  getSaleReceipts,
  addSaleReceipt,
  updateSaleReceipt,
  delSaleReceipt,
  delSaleReceipts,
  getSaleReceiptMaxCode,
  delSaleReceiptDetails,
} from "@/api/sale";
import { getCustomerList } from "@/api/base";
import { getUserList } from "@/api/user";
import { getAccountList } from "@/api/finance";
import { getCurrentDate } from "@/utils/datetime";


const defaultForm = {
  id: null,
  code: "",
  account: null,
  recv_time: getCurrentDate(),
  customer: null,
  user: null,
  receivable: 0,
  amount: 0,
  discount_amount: 0,
  actual_amount: 0,
  oper: null,
  remark: "",
  flag: 0,
  details: [],
};
const defaultItemForm = {
  sale_order: null,
  sale_order_code: null,
  sale_order_time: null,
  receipt_order_time: null,
  sale_order_total_amount: null,
  sale_order_amount: null,
  prepay_total_amount: null,
  amount: 0,
  remark: "",
  category: 0,
  prepay_code: null,
};

export default {
  name: "SaleReceipt",
  data() {
    return {
      form: Object.assign({}, defaultForm),
      itemForm: Object.assign({}, defaultItemForm),
      current_row: null,
      formRules: {
        code: [
          {
            type: "string",
            required: true,
            message: "请输入销售单编号",
            trigger: "blur",
          },
        ],
        recv_time: [
          {
            required: true,
            message: "请输入收款时间",
            trigger: "blur",
          },
        ],
        customer: [
          {
            required: true,
            message: "请选择付款客户",
            trigger: ["blur", "change"],
          },
        ],
        account: [
          {
            required: true,
            message: "请选择收款账户",
            trigger: ["blur", "change"],
          },
        ],
        sale_order: [
          {
            required: true,
            message: "请选择销售单号",
            trigger: ["blur", "change"],
          },
        ],
        amount: [
          {
            required: true,
            message: "请输入本次收款金额",
            trigger: "blur",
          },
        ],
      },

      tableColumns: [
        {
          key: "code",
          title: "收款单编号",
          align: "left",
          width: "140",
        },
        {
          key: "recv_time",
          title: "收款时间",
          align: "center",
          width: "100",
        },
        {
          key: "customer_name",
          title: "付款客户",
          width: "160",
        },
        {
          key: "user_name",
          title: "收款人",
          align: "center",
          width: "80",
        },
        {
          key: "receivable",
          title: "应收款金额",
          align: "center",
          width: "120",
        },
        {
          key: "amount",
          title: "本次收款金额",
          align: "center",
          width: "120",
        },
        {
          key: "discount_amount",
          title: "优惠金额",
          align: "center",
          width: "120",
        },
        {
          key: "actual_amount",
          title: "实际收款",
          align: "center",
          width: "90",
        },
        {
          key: "account_name",
          title: "收款账号",
          align: "center",
          width: "100",
        },
        {
          key: "flag_name",
          title: "支付类型",
          align: "center",
          width: "100",
        },
        {
          key: "oper_name",
          title: "操作人",
          align: "center",
          width: "100",
        },
        {
          key: "remark",
          title: "说明",
          align: "center",
        },
      ],
      
      title: "销售收款单",
      dialogVisible: false,
      dlgCodeVisible: false,

      activeName: "first",
      activeItem: "1",

      dialogType: "new",
      datas: [],
      itemDatas: [],
      customers: [],
      users: [],

      accounts: [],
      selections: [],
      itemSels: [],
      date_type: 3,

      selectedKeys: [],
      props: {
        expandTrigger: "hover",
        value: "id",
        label: "name",
        children: "children",
      },
      //树形
      defaultProps: {
        children: "children",
        label: "name",
      },

      status_items: [
        { id: 0, name: "等待付款" },
        { id: 1, name: "完全付款" },
      ],

      options: [
        { value: 0, label: "当天" },
        { value: 1, label: "本周" },
        { value: 2, label: "本月" },
        { value: 3, label: "最近一月" },
        { value: 4, label: "本年" },
      ],
      pickerOptions,
      total: 0,
      listLoading: true,
      finished: false,

      listQuery: {
        name: "",
        customer: null,
        user: null,
        search_date: [
          moment().add(-30, "days").format("YYYY-MM-DD"),
          moment().format("YYYY-MM-DD"),
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["uid"]),
    getTitle() {
      return this.dialogType == "new"
        ? `新增${this.title}`
        : `编辑${this.title}`;
    },
  },
  components: {
    SaleOrder,
  },
  created() {
    this.getSaleReceiptList();
    this.getCustomers();
    this.getUserCodeList();
    this.getAccountCodeList();
  },
  methods: {
    handleSelectCode() {
      if (this.form.customer == null) {
        this.$message({
          type: "success",
          message: "请选择付款客户!",
        });
        return;
      }
      this.dlgCodeVisible = true;
      this.$nextTick(() => {
        this.$refs.order.init_data(this.form.customer);
      });
    },
    //选择入库单
    getSelections(val) {
      console.log(val)
      for (const obj of val) {
        let row = Object.assign({}, defaultItemForm);
        if(obj.category == 0){
          row.sale_order = obj.id;
          row.sale_order_code = obj.code;
          row.sale_order_time = obj.order_time;
          row.sale_order_total_amount = obj.total_amount.toFixed(2);
          row.sale_order_amount = obj.amount && obj.amount.toFixed(2) || 0;
          row.amount = obj.norecv_amount.toFixed(2);
          row.remark = obj.remark;
          
        } else if( obj.category >= 1){
          row.prepay_code = obj.code;
          row.receipt_order_time = obj.order_time;
          row.prepay_total_amount = obj.total_amount.toFixed(2);
          row.sale_order_amount = obj.amount && obj.amount.toFixed(2) || 0;
          row.amount = obj.norecv_amount.toFixed(2);
          row.remark = obj.remark;
        }
        
        row.category = obj.category;
        this.form.details.push(row);
      }

      this.calcAmounts();
    },
    //时间查询
    // selectChange(val) {
    //   if (val == 0) {
    //     this.listQuery.search_date = [
    //       moment().format("YYYY-MM-DD"),
    //       moment().format("YYYY-MM-DD"),
    //     ];
    //   } else if (val == 1) {
    //     this.listQuery.search_date = [
    //       moment().startOf("week").format("YYYY-MM-DD"),
    //       moment().endOf("week").format("YYYY-MM-DD"),
    //     ];
    //   } else if (val == 2) {
    //     this.listQuery.search_date = [
    //       moment().startOf("month").format("YYYY-MM-DD"),
    //       moment().endOf("month").format("YYYY-MM-DD"),
    //     ];
    //   } else if (val == 3) {
    //     this.listQuery.search_date = [
    //       moment().add(-30, "days").format("YYYY-MM-DD"),
    //       moment().format("YYYY-MM-DD"),
    //     ];
    //   } else if (val == 4) {
    //     this.listQuery.search_date = [
    //       moment().startOf("year").format("YYYY-MM-DD"),
    //       moment().endOf("year").format("YYYY-MM-DD"),
    //     ];
    //   }
    //   this.getSaleReceiptList();
    // },

    discountInput() {
      this.form.actual_amount = this.form.actual_amount.replace(
        /[^\d|.]/g,
        ""
      );
      let discount_amount = this.form.amount - this.form.actual_amount
      this.form.discount_amount = discount_amount.toFixed(2);
    },

    calcAmounts() {
      let sum = 0;
      let pay_amount = 0;

      // 去重
      var hash = {};
      const saleOrders = this.form.details.reduce(function (item, next) {
        hash[next.sale_order_code||next.prepay_code]
          ? ""
          : (hash[next.sale_order_code||next.prepay_code] = true && item.push(next));
        return item;
      }, []);

      for (const row of saleOrders) {
        console.log(row);
        if(row.category == 0){
          sum += parseFloat(row.sale_order_total_amount);
        } else if(row.category >= 1) {
          sum += parseFloat(row.prepay_total_amount);
        }
        
      }

      for (const row of this.form.details) {
        pay_amount += parseFloat(row.amount);
      }

      this.form.receivable = sum.toFixed(2);
      this.form.amount = pay_amount.toFixed(2);
      this.form.discount_amount = 0;
      this.form.actual_amount = this.form.amount - this.form.discount_amount;
    },

    getSaleReceiptMaxCode() {
      getSaleReceiptMaxCode().then((res) => {
        this.form.code = res.max_code;
      });
    },
    getAccountCodeList() {
      getAccountList().then((res) => {
        this.accounts = res;
      });
    },

    getUserCodeList() {
      getUserList().then((res) => {
        this.users = res;
      });
    },

    getCustomers() {
      getCustomerList().then((res) => {
        this.customers = res;
      });
    },

    getSaleReceiptList() {
      this.listLoading = true;
      getSaleReceipts(this.listQuery)
        .then((res) => {
          this.datas = res;
          this.listLoading = false;
          this.finished = true;
        })
        .catch((error) => {
          this.$message.error("获取数据失败:" + error);
          this.listLoading = false;
          this.finished = true;
        });
    },

    handleSelectionChange(val) {
      if (val instanceof Array) {
        this.selections = val.map((item) => item.id);
      }
    },

    handleItemChange(val) {
      this.itemSels = val;
    },

    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.datas = [];
      this.getSaleReceiptList();
    },

    // 删除
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除该记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delSaleReceipt(row.id);

          const index = this.datas.findIndex((v) => v.id == row.id);
          this.datas.splice(index, 1);
          this.itemDatas = [];
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          this.$message({
            type: "fail",
            message: "删除失败:" + err,
          });
        });
    },

    //批量删除
    handleBatchDelete() {
      if (this.selections.length == 0) {
        this.$message.warning("请选择要删除记录");
        return;
      }
      this.$confirm("确定要删除选中记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const sel_ids = {
            select_ids: this.selections,
          };
          const res = await delSaleReceipts(sel_ids);
          this.itemDatas = [];

          this.getSaleReceiptList();

          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          this.$message({
            type: "success",
            message: "删除失败!" + err,
          });
        });
    },

    //批量删除
    deleteItem() {
      // console.log(this.itemSels);
      if (this.itemSels.length == 0) {
        this.$message.warning("请选择要删除记录");
        return;
      }
      this.$confirm("确定要删除选中记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const sel_ids = {
            select_ids: this.itemSels
              .filter((item) => item.id != undefined)
              .map((item) => item.id),
          };

          if (sel_ids.select_ids.length > 0) {
            const res = await delSaleReceiptDetails(sel_ids);
          }

          this.form.details = this.form.details.filter((item) => {
            return !this.itemSels.includes(item);
          });

          if (this.current_row != null) {
            this.current_row.details = this.current_row.details.filter(
              (item) => {
                return !this.itemSels.includes(item);
              }
            );
          }

          if (sel_ids.select_ids.length > 0) {
            this.calcAmounts();
              if(this.dialogType=="edit"){
                updateSaleReceipt(this.form).then(res=>{
                this.getSaleReceiptList();
              });
            }
            
          }

          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          this.$message({
            type: "danger",
            message: "删除失败!" + err,
          });
        });
    },

    addItem() {
      let itemForm = Object.assign({}, defaultItemForm);
      this.form.details.push(itemForm);
    },

    // 增加
    handleAdd() {
      this.form = Object.assign({}, defaultForm);
      this.form.details = [];
      this.getSaleReceiptMaxCode();

      this.dialogType = "new";
      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 修改
    handleEdit(scope) {
      this.current_row = scope.row;
      this.form = JSON.parse(JSON.stringify(scope.row));
      this.dialogType = "edit";

      this.dialogVisible = true;
      this.$nextTick(() => {
        // this.selectedKeys = getParentsPath(key, this.stations);
        this.$refs.formRef.clearValidate();
      });
    },

    // 保存操作
    async handleSave(flag) {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";
        let res = null;
        if (this.form.oper == null || this.form.oper == undefined) {
          this.form.oper = this.uid;
        }
        if (isEdit) {
          console.log(this.form);
          res = await updateSaleReceipt(this.form);
        } else {
          res = await addSaleReceipt(this.form);
        }

        this.getSaleReceiptList();

        const { code, recv_time, customer_name, user_name, amount } = res;

        if (flag) {
          this.form = Object.assign({}, defaultForm);
          this.dialogType = "new";
          this.getSaleReceiptMaxCode();
        } else {
          this.dialogVisible = false;
        }

        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>收款单编号: ${code}</div>
              <div>收款时间: ${recv_time}</div>
              <div>付款客户: ${customer_name}</div>
              <div>收款人: ${user_name}</div>
              <div>收款金额: ${amount}</div>
            `,
          type: "success",
        });
      });
    },

    dataFormatter(column, cellValue) {
      if (
        column == "receivable" ||
        column == "amount" ||
        column == "discount_amount" ||
        column == "actual_amount"
      ) {
        return (
          (cellValue || cellValue === 0) && parseFloat(cellValue).toFixed(2)
        );
      } else {
        return cellValue;
      }
    },

    //合计
    getSummaries(param) {
      const { columns, data } = param;
      console.log(columns);
      console.log(data);

      const sums = [];
      columns.forEach((column, index) => {
        if (index === 2) {
          sums[index] = "合计";
          return;
        }
        if (
          column.property === "receivable" ||
          column.property === "amount" ||
          column.property === "discount_amount" ||
          column.property === "actual_amount"
        ) {
          if (data instanceof Array) {
            const values = data.map((item) => item[column.property]);
            sums[index] = values
              .reduce((prev, curr) => {
                return parseFloat(prev) + parseFloat(curr||0);
              }, 0)
              .toFixed(2);
            sums[index] += " 元";
          }
        } else {
          return;
        }
      });
      return sums;
    },
  },
};
</script>

<style lang='scss' scoped>
.app-container {
  .el-select,
  .el-cascader {
    width: 100%;
  }

  .dialog .el-form {
    margin-top: 20px;
  }
  .el-link {
    font-size: 12px;
  }
  .el-row {
    margin-left: 10px;
  }
}
</style>